﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using CNotebook;
using CNotebook.Sales;
using CNotebook.Inventory;
using System.IO;

namespace NotebookS2
{
    public partial class SalesReturn : RibbonForm
    {
        public SalesReturn()
        {
            InitializeComponent();
        }

        #region Copy to Sales Return
        private string _ReferenceSINo;

        public string ReferenceSINo
        {
            get { return _ReferenceSINo; }
            set { _ReferenceSINo = value; txtRefSINo.Text = value; }
        }



        public bool IsExportedFromSalesInvoice { get; set; }
        public void GetBusinessPartnerDefaults(string sCardCode)
        {
            #region Getting the Default Setup of Customer in BP Master File
            AddressBookManager oBPManager = new AddressBookManager();

            oBPManager.ConnectionString = this.ConnectionString;
            oBPManager.Open();

            this.DefaultPriceList = oBPManager.GetPriceListCode(sCardCode);
            this.WithHoldingTaxRate = oBPManager.GetWithHoldingTaxRate(sCardCode);

            //txtPaymentTerms.Text = oBPManager.GetPaymentTerm(sCardCode);
            //txtDivision.Text = oBPManager.GetDivision(sCardCode);
            oBPManager.Close();
            #endregion


            //dtDeliveryDate.EditValue = ((DateTime)dtPostDate.EditValue).AddDays(Convert.ToInt16(txtPaymentTerms.Text));

            #region Getting the Tax Code Setup
            TaxManager oTxManager = new TaxManager();

            oTxManager.ConnectionString = this.ConnectionString;
            oTxManager.Open();

            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();
            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;

            #endregion


        }

        public void CopyDeliveryToReturn(string _DR_NO)
        {
            DateTime _NOW = System.DateTime.Now;

            InitializeSeries();
            this.IsExportedFromSalesInvoice = true;

            dtPostDate.EditValue = _NOW;
            dtDeliveryDate.EditValue = _NOW;
            dtDocDate.EditValue = _NOW;

            BindWarehouse();                        // Binding the Combo Box Warehouse/Location
            BindSalesMan();                         // Binding Sales Man/Accounts
            BindReturnType();

            if (this.IsMultipleWarehouse == false)  // Enable the Selection of Combo Box if the Users Allowed to Select Multiple Warehouse
            {
                cboLocation.Enabled = false;
            }

            if (txtReference.Text != "")            // Reference Sales Order
            {
                return;
            }
            BindReason(cboReason);

            #region Intializing Line Items


            if (this.ReturnLineItems == null)
            {
                this.ReturnLineItems = GetTable();
            }

            #endregion


            DeliveryManager oManager = new DeliveryManager();

            #region Retrieving the Sales Order - Header


            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            txtReference.Text = _DR_NO;

            DataRow oHeaderRowSO = oManager.GetDelivery(_DR_NO);

            cboLocation.EditValue = oHeaderRowSO["Location"].ToString();
            txtStoreCode.Text = oHeaderRowSO["StoreCode"].ToString();
            txtCardCode.Text = oHeaderRowSO["CardCode"].ToString();
            txtCardName.Text = oHeaderRowSO["CardName"].ToString();
            txtBillTo.Text = oHeaderRowSO["BillTo"].ToString();
            txtShipTo.Text = oHeaderRowSO["ShipTo"].ToString();
            txtContactPerson.Text = oHeaderRowSO["ContactPerson"].ToString();
            cboSalesman.EditValue = oHeaderRowSO["SalesMan"].ToString();
            try
            {
                txtDisc1.Text = oHeaderRowSO["Discount1"].ToString();
                txtDisc2.Text = oHeaderRowSO["Discount2"].ToString();
                txtDisc3.Text = oHeaderRowSO["Discount3"].ToString();
                txtDisc4.Text = oHeaderRowSO["Discount4"].ToString();
            }
            catch
            {
            }
            this.VATCode = oHeaderRowSO["VATCode"].ToString();
            //txtPaymentTerms.Text = oHeaderRowSO["PaymentTerms"].ToString();
            //txtCustRefPO.Text = oHeaderRowSO["Reference"].ToString();
            #endregion

            #region Getting the Default Setup of Customer in BP Master File
            AddressBookManager oBPManager = new AddressBookManager();

            oBPManager.ConnectionString = this.ConnectionString;
            oBPManager.Open();

            this.DefaultPriceList = oBPManager.GetPriceListCode(txtCardCode.Text);
            this.WithHoldingTaxRate = oBPManager.GetWithHoldingTaxRate(txtCardCode.Text);

            oBPManager.Close();
            #endregion

            #region Getting the Tax Code Setup
            TaxManager oTxManager = new TaxManager();

            oTxManager.ConnectionString = this.ConnectionString;
            oTxManager.Open();

            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();
            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;

            #endregion


            #region Getting the DR Line Items

            DataTable dt = oManager.GetDeliveryLineItems(_DR_NO);

            foreach (DataRow row in dt.Rows)
            {
                DataRow rowAdd = this.ReturnLineItems.NewRow();

                rowAdd["ItemCode"] = row["ItemCode"].ToString();
                rowAdd["ItemDesc"] = row["ItemDesc"].ToString();
                rowAdd["UoM"] = row["UoM"].ToString();
                rowAdd["Qty"] = row["Qty"].ToString();
                rowAdd["CQty"] = row["CQty"].ToString();
                rowAdd["Reason"] = "";
                rowAdd["LotNumber"] = row["LotNumber"].ToString();
                rowAdd["UnitPrice"] = row["UnitPrice"].ToString();
                rowAdd["UnitCost"] = row["UnitCost"].ToString();
                rowAdd["IsFree"] = row["IsFree"];
                rowAdd["DiscPrcnt"] = row["DiscPrcnt"];
                rowAdd["Discount"] = row["Discount"];
                rowAdd["TotalLineDisc"] = row["TotalLineDisc"];
                rowAdd["Amount"] = row["Amount"];
                rowAdd["ItemGuid"] = row["ItemGuid"].ToString();
                this.ReturnLineItems.Rows.Add(rowAdd);
            }

            #endregion


            gridControl1.DataSource = this.ReturnLineItems; // Line Items Data Table Binding in Grid
            gridControl1.Refresh();

            if (grdViewSR.DataRowCount <= 0)
            {
                grdViewSR.AddNewRow();
            }
            ComputeTotal();
            ApplyVolumeDiscount();


        }

        public void CopyInvoiceToReturn(string _INVOICE_NO)
        {
            DateTime _NOW = System.DateTime.Now;

            InitializeSeries();
            this.IsExportedFromSalesInvoice = true;

            dtPostDate.EditValue = _NOW;
            dtDeliveryDate.EditValue = _NOW;
            dtDocDate.EditValue = _NOW;

            BindWarehouse();                        // Binding the Combo Box Warehouse/Location
            BindSalesMan();                         // Binding Sales Man/Accounts
            BindReturnType();
          
            if (this.IsMultipleWarehouse == false)  // Enable the Selection of Combo Box if the Users Allowed to Select Multiple Warehouse
            {
                cboLocation.Enabled = false;
            }

            if (txtReference.Text != "")            // Reference Sales Order
            {
                return;
            }
            BindReason(cboReason);

            #region Intializing Line Items
        

            if (this.ReturnLineItems == null)
            {
                this.ReturnLineItems = GetTable();
            }

            #endregion


            InvoiceManager oManager = new InvoiceManager();

            #region Retrieving the Sales Order - Header


            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            txtReference.Text = _INVOICE_NO;

            DataRow oHeaderRowSO = oManager.GetInvoice(_INVOICE_NO);

            cboLocation.EditValue = oHeaderRowSO["Location"].ToString();
            txtStoreCode.Text = oHeaderRowSO["StoreCode"].ToString();
            txtCardCode.Text = oHeaderRowSO["CardCode"].ToString();
            txtCardName.Text = oHeaderRowSO["CardName"].ToString();
            txtBillTo.Text = oHeaderRowSO["BillTo"].ToString();
            txtShipTo.Text = oHeaderRowSO["ShipTo"].ToString();
            txtContactPerson.Text = oHeaderRowSO["ContactPerson"].ToString();
            cboSalesman.EditValue = oHeaderRowSO["SalesMan"].ToString();
            try
            {
                txtDisc1.Text = oHeaderRowSO["Discount1"].ToString();
                txtDisc2.Text = oHeaderRowSO["Discount2"].ToString();
                txtDisc3.Text = oHeaderRowSO["Discount3"].ToString();
                txtDisc4.Text = oHeaderRowSO["Discount4"].ToString();
            }
            catch
            {
            }
            this.VATCode = oHeaderRowSO["VATCode"].ToString();
            //txtPaymentTerms.Text = oHeaderRowSO["PaymentTerms"].ToString();
            //txtCustRefPO.Text = oHeaderRowSO["Reference"].ToString();
            #endregion

            #region Getting the Default Setup of Customer in BP Master File
            AddressBookManager oBPManager = new AddressBookManager();

            oBPManager.ConnectionString = this.ConnectionString;
            oBPManager.Open();

            this.DefaultPriceList = oBPManager.GetPriceListCode(txtCardCode.Text);
            this.WithHoldingTaxRate = oBPManager.GetWithHoldingTaxRate(txtCardCode.Text);

            oBPManager.Close();
            #endregion

            #region Getting the Tax Code Setup
            TaxManager oTxManager = new TaxManager();

            oTxManager.ConnectionString = this.ConnectionString;
            oTxManager.Open();

            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();
            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;

            #endregion


            #region Getting the DR Line Items 

            DataTable dt = oManager.GetInvoiceLineItems(_INVOICE_NO);

            foreach (DataRow row in dt.Rows)
            {
                DataRow rowAdd = this.ReturnLineItems.NewRow();

                rowAdd["ItemCode"] = row["ItemCode"].ToString();
                rowAdd["ItemDesc"] = row["ItemDesc"].ToString();
                rowAdd["UoM"] = row["UoM"].ToString();
                rowAdd["Qty"] = row["Qty"].ToString();
                rowAdd["CQty"] = row["CQty"].ToString();
                rowAdd["Reason"] = "";
                rowAdd["LotNumber"] = row["LotNumber"].ToString();
                rowAdd["UnitPrice"] = row["UnitPrice"].ToString();
                rowAdd["UnitCost"] = row["UnitCost"].ToString();
                rowAdd["IsFree"] = row["IsFree"];
                rowAdd["DiscPrcnt"] = row["DiscPrcnt"];
                rowAdd["Discount"] = row["Discount"];
                rowAdd["TotalLineDisc"] = row["TotalLineDisc"];
                rowAdd["Amount"] = row["Amount"];
                rowAdd["ItemGuid"] = row["ItemGuid"].ToString();
                this.ReturnLineItems.Rows.Add(rowAdd);
            }

            #endregion


            gridControl1.DataSource = this.ReturnLineItems; // Line Items Data Table Binding in Grid
            gridControl1.Refresh();

            if (grdViewSR.DataRowCount <= 0)
            {
                grdViewSR.AddNewRow();
            }
            ComputeTotal();
            ApplyVolumeDiscount();


        }

        #endregion

        #region Properties
        public string ConnectionString { get; set; }
        public string ActiveUserID { get; set; }
        public bool IsMultipleWarehouse { get; set; }
        public string DefaultWarehouse { get; set; }

        public DataTable ReturnLineItems { get; set; }
        public DataTable AccountingEntries { get; set; }

        public string DefaultPriceList { get; set; }
        public double WithHoldingTaxRate { get; set; }
        public string VATCode { get; set; }
        public string VATRate { get; set; }
        public bool IsInclusive { get; set; }
        public Keys UsedKey = Keys.None;
        #endregion
        
        #region Initialization

        void BindUoM(string sItemCode, DevExpress.XtraEditors.Repository.RepositoryItemComboBox oCbo)
        {
            UoMManager oManager = new UoMManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable _table = oManager.GetUnitMeasures(sItemCode);

            oManager.Close();

            oCbo.Items.Clear();
            foreach (DataRow oRow in _table.Rows)
            {
                oCbo.Items.Add(oRow["UoM"].ToString());
            }

        }

        private void BindLotNumber(string sItemCode, DevExpress.XtraEditors.Repository.RepositoryItemComboBox oCbo)
        {
            StockManager oManager = new StockManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable _table = oManager.GetLotNumbers(sItemCode);

            oManager.Close();
            oCbo.Items.Clear();
            foreach (DataRow oRow in _table.Rows)
            {
                oCbo.Items.Add(oRow["LotNumber"].ToString());
            }
           
        }

        private void BindReason(DevExpress.XtraEditors.Repository.RepositoryItemComboBox oCboReason)
        {
            SalesReturnManager oManager = new SalesReturnManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable _table = oManager.GetReturnReasons();

            oManager.Close();

            foreach (DataRow oRow in _table.Rows)
            {
                oCboReason.Items.Add(oRow["ReasonDesc"].ToString());
            }

        }

        private static DataTable GetTable()
        {
            DataTable table = new DataTable();

            table.Columns.Add("ItemCode", typeof(string));
            table.Columns.Add("ItemDesc", typeof(string));
            table.Columns.Add("UoM", typeof(string));
            table.Columns.Add("Qty", typeof(double));
            table.Columns.Add("CQty", typeof(double));
            table.Columns.Add("Reason", typeof(string));
            table.Columns.Add("LotNumber", typeof(string));
            table.Columns.Add("PriceListCode", typeof(string));
            table.Columns.Add("UnitCost", typeof(double));
            table.Columns.Add("UnitPrice", typeof(double));
            table.Columns.Add("IsFree", typeof(bool));
            table.Columns.Add("DiscPrcnt", typeof(double));
            table.Columns.Add("Discount", typeof(double));
            table.Columns.Add("TotalLineDisc", typeof(double));
            table.Columns.Add("Amount", typeof(double));
            table.Columns.Add("ItemGuid", typeof(string));
            
            return table;

        }

        private static DataTable GetGLAcctStructure()
        {
            DataTable table = new DataTable();

            table.Columns.Add("TransDate", typeof(DateTime));
            table.Columns.Add("TransType", typeof(string));
            table.Columns.Add("TransNum", typeof(string));

            table.Columns.Add("AcctCode", typeof(string));
            table.Columns.Add("AcctName", typeof(string));
            table.Columns.Add("Particulars", typeof(string));
            table.Columns.Add("DebitAmt", typeof(double));
            table.Columns.Add("CreditAmt", typeof(double));

            return table;

        }

        void InitializeSeries()
        {

            string sOrderSeries = "4";
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();

            lblValidUntilDeliveryDate.Text = "Due Date:";
            if (oSeries.IsAutoNumber(sOrderSeries) == true)
            {
                txtDocumentNumber.Properties.ReadOnly = true;
                txtDocumentNumber.Text = "##########";

            }
            oSeries.Close();
 
        }
        
        #endregion

        #region Functions
        void RemoveBlankLastGLAccounts()
        {

            int iRowIndex = gridViewSalesRetAcctEntries.RowCount;
            gridViewSalesRetAcctEntries.FocusedRowHandle = iRowIndex - 1;
            try
            {
                string _AcctCode = "";


                if (gridViewSalesRetAcctEntries.GetRowCellValue(gridViewSalesRetAcctEntries.FocusedRowHandle, gridViewSalesRetAcctEntries.Columns["AcctCode"]) != null)
                {
                    _AcctCode = gridViewSalesRetAcctEntries.GetRowCellValue(gridViewSalesRetAcctEntries.FocusedRowHandle, gridViewSalesRetAcctEntries.Columns["AcctCode"]).ToString();
                }
                else
                {
                    _AcctCode = "";
                }

                if (_AcctCode.Trim() == "")
                {
                    gridViewSalesRetAcctEntries.DeleteRow(gridViewSalesRetAcctEntries.FocusedRowHandle);
                }
            }
            catch { }

        }

        public string GetDiscountMethod()
        {
            string sPath = System.Windows.Forms.Application.StartupPath.ToString() + "\\config.conf";
            string _OUTPUT_STRING = "";


            if (File.Exists(sPath) == true)
            {


                StreamReader sr = File.OpenText(sPath);
                string input;

                do
                {
                    input = sr.ReadLine();
                    if (input != null)
                    {

                        if (input.StartsWith("DiscountMethod") == true)
                        {
                            int iStart = input.IndexOf("=");
                            _OUTPUT_STRING = input.Substring(iStart + 1);

                            break;
                        }

                    }
                } while (input != null);


            }
            return _OUTPUT_STRING;

        }

        public void PrintPreview()
        {
            PRNT_RET oPrint = new PRNT_RET();

            oPrint.ConnectionString = this.ConnectionString;
            oPrint.DocumentNumber = txtDocumentNumber.Text;

            oPrint.WindowState = FormWindowState.Maximized;
            oPrint.ShowDialog();
        }

        void DisableControls()
        {
            cboLocation.Enabled = false;
            txtStoreCode.Enabled = false;
            txtCardCode.Enabled = false;
            txtCardName.Enabled = false;
            txtContactPerson.Enabled = false;
            txtReference.Enabled = false;
            txtRef1.Enabled = false;
            txtRef2.Enabled = false;
            txtRef3.Enabled = false;
            txtBillTo.Enabled = false;
            txtShipTo.Enabled = false;
            txtDocumentNumber.Enabled = false;
            dtPostDate.Enabled = false;
            dtDeliveryDate.Enabled = false;
            dtDocDate.Enabled = false;
            
            cboSalesman.Enabled = false;
            txtRemarks.Enabled = false;
            cboReturnType.Enabled = false;
            txtGrossAmount.Enabled = false;
            txtTotalLineDiscount.Enabled = false;
            txtDisc1.Enabled = false;
            txtDisc2.Enabled = false;
            txtDisc3.Enabled = false;
            txtDisc4.Enabled = false;
            txtTotalDiscount.Enabled = false;
            txtVAT.Enabled = false;
            txtNetAmt.Enabled = false;

            btnAdd.Enabled = false;
            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in grdViewSR.Columns)
            {
                oColumn.OptionsColumn.AllowEdit = false;
            }
            
        }

        void EnableControls()
        {
            cboLocation.Enabled = true;
            txtStoreCode.Enabled = true;
            txtCardCode.Enabled = true;
            txtCardName.Enabled = true;
            txtContactPerson.Enabled = true;
            txtReference.Enabled = true;
            txtRef1.Enabled = true;
            txtRef2.Enabled = true;
            txtRef3.Enabled = true;
            txtBillTo.Enabled = true;
            txtShipTo.Enabled = true;
            txtDocumentNumber.Enabled = true;
            dtPostDate.Enabled = true;
            dtDeliveryDate.Enabled = true;
            dtDocDate.Enabled = true;

            cboSalesman.Enabled = true;
            txtRemarks.Enabled = true;
            cboReturnType.Enabled = true;
            txtGrossAmount.Enabled = true;
            txtTotalLineDiscount.Enabled = true;
            txtDisc1.Enabled = true;
            txtDisc2.Enabled = true;
            txtDisc3.Enabled = true;
            txtDisc4.Enabled = true;
            txtTotalDiscount.Enabled = true;
            txtVAT.Enabled = true;
            txtNetAmt.Enabled = true;

            btnAdd.Enabled = true;
            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in grdViewSR.Columns)
            {
                oColumn.OptionsColumn.AllowEdit = true;
            }

        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _DOCTYPE = "4";

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_DOCTYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_DOCTYPE);
            }
            else
            {
                _SERIES = txtDocumentNumber.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        private void ComputeTotal()
        {
            try
            {
                double _GrossAmount = 0;
                double _NetAmount = 0;
                double _LineDiscount = 0;

                foreach (DataRow oRow in this.ReturnLineItems.Rows)
                {

                    if (oRow["Amount"] != DBNull.Value)
                    {
                        bool IsFree = false;
                        if (oRow["IsFree"] != DBNull.Value)
                        {
                            IsFree = Convert.ToBoolean(oRow["IsFree"]);
                        }
                        else
                        {
                            IsFree = false;
                        }


                        if (IsFree == false)
                        {
                            _GrossAmount = _GrossAmount + (Convert.ToDouble(oRow["Qty"]) * Convert.ToDouble(oRow["CQty"])) * Convert.ToDouble(oRow["UnitPrice"]);
                            _NetAmount = _NetAmount + (Convert.ToDouble(oRow["Amount"]));
                            if (oRow["TotalLineDisc"] == DBNull.Value)
                            {
                                oRow["TotalLineDisc"] = 0;
                            }
                            _LineDiscount = _LineDiscount + (Convert.ToDouble(oRow["TotalLineDisc"]));
                        }
                    }
                }

                double _VAT = 0;

                double _VolumeDiscount = Convert.ToDouble(txtTotalDiscount.Text);


                if (this.VATCode == "VAT Inclusive")
                {
                    if (this.IsInclusive == true)
                    {

                        _VAT = _NetAmount - (_NetAmount / Convert.ToDouble(this.VATRate));
                        _VAT = Convert.ToDouble(_VAT.ToString("##.00"));
                        txtVAT.Text = _VAT.ToString();

                        //txtWithHoldingTax.Text = Convert.ToString(((_NetAmount / Convert.ToDouble(this.VATRate)) * (this.WithHoldingTaxRate / 100)).ToString("##.00"));

                    }
                    else
                    {
                        txtVAT.Text = "0";
                    }

                }

                if (this.VATCode == "VAT Exclusive")
                {
                    if (this.IsInclusive == false)
                    {
                        _VAT = _NetAmount * Convert.ToDouble(this.VATRate);
                        _VAT = Convert.ToDouble(_VAT.ToString("##.00"));
                        txtVAT.Text = _VAT.ToString();

                        //txtWithHoldingTax.Text = Convert.ToString((_NetAmount * (this.WithHoldingTaxRate / 100)).ToString("##.00"));
                    }
                    else
                    {
                        txtVAT.Text = "0";
                    }
                }

                txtTotalLineDiscount.Text = _LineDiscount.ToString("#,###.00");
                txtGrossAmount.Text = _GrossAmount.ToString("#,###.00");

                txtNetAmt.Text = _NetAmount.ToString("#,###.00");
                txtWithHoldingTax.Text = ((_NetAmount - _VolumeDiscount) * (this.WithHoldingTaxRate / 100)).ToString();



            }
            catch
            {
            }

        }

        private void ApplyVolumeDiscount()
        {

            double _GrossAmount = 0;
            double _NetAmount = 0;
            double _TotalLineDiscount = 0;
            double _VatAmount = 0;

            foreach (DataRow oRow in this.ReturnLineItems.Rows)
            {

                if (oRow.RowState != DataRowState.Deleted)
                {
                    if (oRow["CQty"] == DBNull.Value)
                    {
                        oRow["CQty"] = 0;
                    }

                    if (oRow["Qty"] == DBNull.Value)
                    {
                        oRow["Qty"] = 0;
                    }
                    if (oRow["UnitPrice"] == DBNull.Value)
                    {
                        oRow["UnitPrice"] = 0;
                    }
                    if (oRow["TotalLineDisc"] == DBNull.Value)
                    {
                        oRow["TotalLineDisc"] = 0;
                    }
                    if (oRow["IsFree"] == DBNull.Value)
                    {
                        oRow["IsFree"] = false;
                    }
                    bool IsFree = Convert.ToBoolean(oRow["IsFree"]);

                    if (IsFree != true)
                    {
                        _GrossAmount = _GrossAmount + (Convert.ToDouble(oRow["Qty"]) * Convert.ToDouble(oRow["CQty"])) * Convert.ToDouble(oRow["UnitPrice"]);
                        _TotalLineDiscount = _TotalLineDiscount + Convert.ToDouble(oRow["TotalLineDisc"]);
                    }
                }

            }

            txtDisc1.Text = txtDisc1.Text.Replace("%", "");
            txtDisc2.Text = txtDisc2.Text.Replace("%", "");
            txtDisc3.Text = txtDisc3.Text.Replace("%", "");
            txtDisc4.Text = txtDisc4.Text.Replace("%", "");


            string sDiscount1 = txtDisc1.Text.Replace("%", "");
            string sDiscount2 = txtDisc2.Text.Replace("%", "");
            string sDiscount3 = txtDisc3.Text.Replace("%", "");
            string sDiscount4 = txtDisc4.Text.Replace("%", "");


            double _disc1 = 0;
            double _disc2 = 0;
            double _disc3 = 0;
            double _disc4 = 0;


            _disc1 = Convert.ToDouble(sDiscount1);
            _disc2 = Convert.ToDouble(sDiscount2);
            _disc3 = Convert.ToDouble(sDiscount3);

            double _TotalDiscount = 0;

            double _discount1 = 0;
            double _discount2 = 0;
            double _discount3 = 0;
            double _discount4 = 0;

            _disc1 = Convert.ToDouble(sDiscount1);
            _disc2 = Convert.ToDouble(sDiscount2);
            _disc3 = Convert.ToDouble(sDiscount3);


            if (txtDisc4.Text == "")
            {
                _disc4 = 0;
            }
            else
            {
                _disc4 = Convert.ToDouble(sDiscount4);
            }

            if (_disc1 > 0)
            {
                _discount1 = (_GrossAmount - _TotalLineDiscount) * (_disc1 / 100);

                _TotalDiscount = (_GrossAmount - _TotalLineDiscount) - _discount1;
            }
            if (_disc2 > 0)
            {
                _discount2 = (_TotalDiscount * (_disc2 / 100));
                _TotalDiscount = _TotalDiscount - _discount2;

            }
            if (_disc3 > 0)
            {
                _discount3 = (_TotalDiscount * (_disc3 / 100));
                _TotalDiscount = _TotalDiscount - _discount3;
            }

            if (_disc4 > 0)
            {
                _discount4 = (_TotalDiscount * (_disc4 / 100));
                _TotalDiscount = _TotalDiscount - _discount4;
            }

            _TotalDiscount = (_discount1 + _discount2 + _discount3 + _discount4);
            txtTotalDiscount.Text = _TotalDiscount.ToString("#,###.00");



            txtGrossAmount.Text = _GrossAmount.ToString("#,###.00");
            txtTotalLineDiscount.Text = _TotalLineDiscount.ToString("#,###.00");

            _NetAmount = (_GrossAmount - _TotalDiscount) - _TotalLineDiscount;


            string _DISCOUNT_METHOD = GetDiscountMethod();
            if (this.VATCode != "NON-VAT")
            {
                if (_DISCOUNT_METHOD == "After")
                {
                    if (this.VATCode == "VAT Inclusive")
                    {
                        _VatAmount = _NetAmount - (_NetAmount / Convert.ToDouble(this.VATRate));
                    }
                    else if (this.VATCode == "VAT Exclusive")
                    {
                        _VatAmount = _NetAmount * Convert.ToDouble(this.VATRate);
                        _NetAmount = _NetAmount + _VatAmount;
                    }
                }
                else
                {
                    if (this.VATCode == "VAT Inclusive")
                    {
                        _VatAmount = _GrossAmount - (_GrossAmount / Convert.ToDouble(this.VATRate));
                    }
                    else if (this.VATCode == "VAT Exclusive")
                    {
                        _VatAmount = _GrossAmount * Convert.ToDouble(this.VATRate);
                        _NetAmount = ((_GrossAmount + _VatAmount) - (_TotalDiscount - _TotalDiscount));
                    }
                }
            }




            txtVAT.Text = _VatAmount.ToString("#,###.00");
            txtNetAmt.Text = _NetAmount.ToString("#,###.00");
            txtWithHoldingTax.Text = (_NetAmount * (this.WithHoldingTaxRate / 100)).ToString();

            #region Returning Percent Sign
            if (_disc1 > 0)
            {
                txtDisc1.Text = _disc1.ToString("#.00") + "%";
            }
            else
            {
                txtDisc1.Text = "0%";
            }
            if (_disc2 > 0)
            {
                txtDisc2.Text = _disc2.ToString("#.00") + "%";
            }
            else
            {
                txtDisc2.Text = "0%";
            }
            if (_disc3 > 0)
            {
                txtDisc3.Text = _disc3.ToString("#.00") + "%";
            }
            else
            {
                txtDisc3.Text = "0%";
            }

            if (_disc4 > 0)
            {
                txtDisc4.Text = _disc4.ToString("#.00") + "%";
            }
            else
            {
                txtDisc4.Text = "0%";
            }
            #endregion


        }

        void BindReturnType()
        {
            SalesReturnManager oManager = new SalesReturnManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable dtReturnType = oManager.GetReturnTypes();

            oManager.Close();

            cboReturnType.Properties.Items.Clear();

            foreach (DataRow row in dtReturnType.Rows)
            {
                cboReturnType.Properties.Items.Add(row["Dscription"].ToString());
            }

        }

        void BindWarehouse()
        {
            WarehouseManager oManager = new WarehouseManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable oTable = new DataTable();

            oTable = oManager.GetWarehouse();
            cboLocation.Visible = false;
            cboLocation.Properties.DataSource = oTable;
            cboLocation.Properties.DisplayMember = "Dscription";
            cboLocation.Properties.ValueMember = "Code";
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Dscription", "Dscription", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboLocation.Properties.Columns.Add(col);
            cboLocation.Properties.ShowHeader = false;
            cboLocation.Visible = true;
            cboLocation.Refresh();

            oManager.Close();
        }
        
        void BindSalesMan()
        {
            AccountManager oManager = new AccountManager();
            DataTable oTable = new DataTable();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();


            oTable = oManager.GetAccounts("Salesman");
            cboSalesman.Visible = false;    
            cboSalesman.Properties.DataSource = oTable;
            cboSalesman.Properties.DisplayMember = "AcctName";
            cboSalesman.Properties.ValueMember = "AcctCode";

            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("AcctCode", "AcctName", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboSalesman.Refresh();
            cboSalesman.Visible = true;
            oManager.Close();

        }

        void RemoveBlankLastRowFirst()
        {
            
            grdViewSR.MoveLast();
            int iFocusedRowHandle = grdViewSR.FocusedRowHandle;
            
            string sItemCode = "";

            try
            {
                sItemCode = grdViewSR.GetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["ItemCode"]).ToString();
            }
            catch { sItemCode = ""; }

            if (sItemCode.Trim() == "")
            {
                grdViewSR.DeleteRow(iFocusedRowHandle);
            }


        }

        public void ShowSearch()
        {
            FND_RET oSearchDocument = new FND_RET();

            oSearchDocument.ConnectionString = this.ConnectionString;
            oSearchDocument.ShowDialog();

            string sDocumentNumber = oSearchDocument.DocumentNumber;


            if (sDocumentNumber != null || sDocumentNumber.Trim() != "")
            {
                SalesReturnManager oManager = new SalesReturnManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataRow oRow = oManager.GetReturn(sDocumentNumber);
             

                #region Header 
                txtDocumentNumber.Text = oRow["DocNum"].ToString();
                txtStatus.Text = oRow["DocStatus"].ToString();
                dtPostDate.EditValue = (DateTime)oRow["PostingDate"];
                dtDeliveryDate.EditValue = (DateTime)oRow["DueDate"];
                dtDocDate.EditValue = (DateTime)oRow["DocDate"];

                txtStoreCode.EditValue = oRow["StoreCode"].ToString();
                txtCardCode.EditValue = oRow["CardCode"].ToString();
                AddressBookManager oCardManager = new AddressBookManager();
                oCardManager.Connection = oManager.Connection;
                this.DefaultPriceList = oCardManager.GetPriceListCode(txtCardCode.Text);
                txtCardName.EditValue = oRow["CardName"].ToString();
                txtContactPerson.EditValue = oRow["ContactPerson"].ToString();
                txtReference.EditValue = oRow["Reference"].ToString();
                txtRef1.EditValue = oRow["Ref1"].ToString();
                txtRef2.EditValue = oRow["Ref2"].ToString();
                txtRef3.EditValue = oRow["Ref3"].ToString();
                txtBillTo.EditValue = oRow["BillTo"].ToString();
                txtShipTo.EditValue = oRow["ShipTo"].ToString();
                cboSalesman.EditValue = oRow["SalesMan"].ToString();
                txtRemarks.EditValue = oRow["Remarks"].ToString();
                cboReturnType.EditValue = oRow["ReturnType"].ToString();
                cboLocation.EditValue = oRow["Location"].ToString();
                //if (oRow["Location"] != DBNull.Value)
                //{
                //    cboLocation.EditValue = oRow["Location"].ToString();
                //}


                if (oRow["VATCode"] != DBNull.Value)
                {
                    this.VATCode = oRow["VATCode"].ToString();
                }

                this.VATRate = oRow["VATRate"].ToString();
                txtWithHoldingTax.Text = oRow["WithHoldingTax"].ToString();

                if (oRow["IsVATInclusive"] != DBNull.Value)
                {

                    if (oRow["IsVATInclusive"].ToString() == "Y")
                    {
                        this.IsInclusive = true;
                    }
                    else
                    {
                        this.IsInclusive = false;
                    }
                }

                txtGrossAmount.EditValue = oRow["GrossAmount"].ToString();
                txtVAT.EditValue = oRow["VATAmount"].ToString();
                txtDisc1.EditValue = oRow["Discount1"].ToString();
                txtDisc2.EditValue = oRow["Discount2"].ToString();
                txtDisc3.EditValue = oRow["Discount3"].ToString();
                txtDisc4.EditValue = oRow["Discount4"].ToString();
                txtTotalDiscount.EditValue = oRow["TotalDiscount"].ToString();
                txtNetAmt.EditValue = oRow["NetAmount"].ToString();
                #endregion

                #region Line Items
                this.ReturnLineItems = oManager.GetReturnLineItems(sDocumentNumber);
                gridControl1.DataSource = this.ReturnLineItems;
                gridControl1.Refresh();


                if (txtStatus.Text == "Draft")
                {
                    if (grdViewSR.RowCount == 0)
                    {
                        grdViewSR.AddNewRow();
                    }
                }

                #endregion


                #region Distributed Accounts
                this.AccountingEntries = oManager.GetAccountingDistribution(sDocumentNumber);

                gridSalesRetAcctEntries.DataSource = this.AccountingEntries;
                gridSalesRetAcctEntries.Refresh();

                #endregion

                oManager.Close();


                btnAdd.Text = "Ok";
                GetBusinessPartnerDefaults(txtCardCode.Text);

                ComputeTotal();
                ApplyVolumeDiscount();
                txtDocumentNumber.Enabled = false;

            }

            string _USR_AUTHORIZATION = ApplyAuthorization();
            if (_USR_AUTHORIZATION == "No Access")
            {
                btnCancel_Click(null, null);
            }

        }

        void CancelOrder(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to cancel this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                SalesReturnManager oManager = new SalesReturnManager();
                SalesReturnUnit oUnit = new SalesReturnUnit();

                #region Update Sales Return

                #region Header Sales Quote

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.Ref1 = txtRef1.Text;
                oUnit.Ref2 = txtRef2.Text;
                oUnit.Ref3 = txtRef3.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                //if (cboLocation.SelectedValue != null)
                //{
                //    oUnit.Location = cboLocation.SelectedValue.ToString();
                //}
                //else
                //{
                //    oUnit.Location = "";
                //}

                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;
                oUnit.ReturnType = cboReturnType.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }



                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.ModifiedBy = this.ActiveUserID;
                #endregion

                oUnit.LineItems = this.ReturnLineItems;

                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateReturn(oUnit);
                oManager.Close();


                #endregion

                #endregion

                oManager = new SalesReturnManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.CancelOrder(sDocNumber);
                oManager.Close();

                if (txtRefSINo.Text.Trim() != "")
                {
                    InvoiceManager oInvoicing = new InvoiceManager();

                    oInvoicing.ConnectionString = this.ConnectionString;

                    oInvoicing.Open();

                    oInvoicing.PostDocument(txtRefSINo.Text, this.ActiveUserID);

                    oInvoicing.Close();

                }
                else
                {
                    DeliveryManager oDR = new DeliveryManager();

                    oDR.ConnectionString = this.ConnectionString;
                    oDR.Open();

                    oDR.PostDocument(txtReference.Text, this.ActiveUserID);

                    oDR.Close();
                }

                txtStatus.Text = "Canceled";
            }

        }

        void PostOrder(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to post this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                SalesReturnManager oManager = new SalesReturnManager();
                SalesReturnUnit oUnit = new SalesReturnUnit();

                #region Update Sales Return

                #region Header Sales Quote

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.Ref1 = txtRef1.Text;
                oUnit.Ref2 = txtRef2.Text;
                oUnit.Ref3 = txtRef3.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                //if (cboLocation.SelectedValue != null)
                //{
                //    oUnit.Location = cboLocation.SelectedValue.ToString();
                //}
                //else
                //{
                //    oUnit.Location = "";
                //}

                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;
                oUnit.ReturnType = cboReturnType.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }



                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.ModifiedBy = this.ActiveUserID;
                #endregion

                oUnit.LineItems = this.ReturnLineItems;

                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateReturn(oUnit);
                oManager.Close();

                
                #endregion

                #endregion

                oManager = new SalesReturnManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.PostOrder(cboLocation.EditValue.ToString(), txtReference.Text, sDocNumber, this.ActiveUserID);
                oManager.Close();

                txtStatus.Text = "Posted";

                DeliveryManager oDRManager = new DeliveryManager();

                oDRManager.ConnectionString = this.ConnectionString;
                oDRManager.Open();

                oDRManager.SetAppliedAmount(txtReference.Text, txtNetAmt.Text);

                oDRManager.Close();

                InvoiceManager oInvManager = new InvoiceManager();
                oInvManager.ConnectionString = this.ConnectionString;
                oInvManager.Open();

                oInvManager.SetAppliedAmount(txtRefSINo.Text, txtNetAmt.Text);

                oInvManager.Close();

                


            }
        }

        void CloseOrder(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to close this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                SalesReturnManager oManager = new SalesReturnManager();
                SalesReturnUnit oUnit = new SalesReturnUnit();

                #region Update Sales Return

                #region Header Sales Quote

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.Ref1 = txtRef1.Text;
                oUnit.Ref2 = txtRef2.Text;
                oUnit.Ref3 = txtRef3.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                //if (cboLocation.SelectedValue != null)
                //{
                //    oUnit.Location = cboLocation.SelectedValue.ToString();
                //}
                //else
                //{
                //    oUnit.Location = "";
                //}

                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;
                oUnit.ReturnType = cboReturnType.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }



                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.ModifiedBy = this.ActiveUserID;
                #endregion

                oUnit.LineItems = this.ReturnLineItems;

                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateReturn(oUnit);
                oManager.Close();


                #endregion

                #endregion

                oManager = new SalesReturnManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.CloseOrder(sDocNumber);
                oManager.Close();

                txtStatus.Text = "Closed";
               
            }
        }
        #endregion

        public int ObjectType { get { return 2; } }


        string ApplyAuthorization()
        {
            UserManager oManager = new UserManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            string iAccessType = oManager.GetAccessType(this.ObjectType, this.ActiveUserID);

            oManager.Close();

            switch (iAccessType)
            {
                case "Full Access":
                    FullAccess();
                    break;
                case "Read Only":
                    ApplyReadOnly();
                    break;
                case "No Access":
                    NoAccess();
                    break;
            }

            return iAccessType;
        }


        int ApplyReadOnly()
        {
            DisableControls();

            txtStatus.Properties.Buttons[0].Enabled = false;
            txtStatus.Properties.Buttons[1].Enabled = false;


            return 2;
        }

        int FullAccess()
        {
            txtStatus.Properties.Buttons[0].Enabled = true;
            txtStatus.Properties.Buttons[1].Enabled = true;

            return 1;
        }

        int NoAccess()
        {
            MessageBox.Show("You have no right to access this module!!!!", "Security Policy", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return 3;

        }



        #region Form Events



        private void SalesReturn_Load(object sender, EventArgs e)
        {
            #region GL Accounts
            if (this.AccountingEntries == null)
            {
                this.AccountingEntries = GetGLAcctStructure();
            }

            gridSalesRetAcctEntries.DataSource = this.AccountingEntries;
            gridSalesRetAcctEntries.Refresh();

            if (gridViewSalesRetAcctEntries.DataRowCount <= 0)
            {
                gridViewSalesRetAcctEntries.AddNewRow();
            }
            #endregion

            if (this.IsExportedFromSalesInvoice == false)
            {
                dtPostDate.EditValue = System.DateTime.Now;
                dtDeliveryDate.EditValue = System.DateTime.Now;
                dtDocDate.EditValue = System.DateTime.Now;

                BindWarehouse();
                BindReturnType();

                cboLocation.EditValue = this.DefaultWarehouse;
                if (this.IsMultipleWarehouse == false)
                {
                    cboLocation.Enabled = false;
                }

                BindSalesMan();
                BindReason(cboReason);
                if (this.ReturnLineItems == null)
                {
                    this.ReturnLineItems = GetTable();
                }

                gridControl1.DataSource = this.ReturnLineItems;
                gridControl1.Refresh();

                if (grdViewSR.DataRowCount <= 0)
                {
                    grdViewSR.AddNewRow();
                }




                InitializeSeries();
            }
            
        }

        private void txtBPCode_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_BP _SearchBP = new FND_BP();

            AddressBookManager oBPManager = new AddressBookManager();
            TaxManager oTxManager = new TaxManager();

            try
            {
                _SearchBP.ConnectionString = this.ConnectionString;
                _SearchBP.BusinessPartnerType = "Customer";
                _SearchBP.ShowDialog();

                txtStoreCode.Text = _SearchBP.StoreCode;
                txtCardCode.Text = _SearchBP.CardCode;
                txtCardName.Text = _SearchBP.CardName;
                txtBillTo.Text = _SearchBP.Address;
                //txtPaymentTerms.Text = _SearchBP.PaymentTerm.ToString();
                txtContactPerson.Text = _SearchBP.ContactPerson;
                this.DefaultPriceList = _SearchBP.PriceList;
                this.WithHoldingTaxRate = _SearchBP.WithHoldingTax;
                this.VATCode = _SearchBP.VATCode;
                try
                {
                    txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                    txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                    txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                    txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                }
                catch
                {
                }

                //cboCurrency.Text 
                oTxManager.ConnectionString = this.ConnectionString;
                oTxManager.Open();


                this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;



                oTxManager.Close();

                if (_SearchBP.BuyerSalesMan != "")
                {
                    cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                }

                _SearchBP.Dispose();
            }
            catch
            {
            }
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (txtStatus.Text == "Draft" && btnAdd.Text == "Ok")
            {
                btnAdd.Text = "Update";
            }

            try
            {
                int iFocusedRowHandle = -1;

                iFocusedRowHandle = grdViewSR.FocusedRowHandle;

                if (e.KeyCode == Keys.Delete)
                {
                    if (txtStatus.Text == "Draft")
                    {
                        if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {

                            if (grdViewSR.IsLastRow)
                            {
                                string sItemCode = "";

                                iFocusedRowHandle = grdViewSR.FocusedRowHandle;

                                sItemCode = grdViewSR.GetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["ItemCode"]).ToString();


                                if (sItemCode != "")
                                {
                                    grdViewSR.DeleteRow(iFocusedRowHandle);
                                    grdViewSR.AddNewRow();
                                }

                                
                                grdViewSR.RefreshData();

                            }
                            else
                            {


                                iFocusedRowHandle = grdViewSR.FocusedRowHandle;
                                grdViewSR.DeleteRow(iFocusedRowHandle);
                                
                                grdViewSR.RefreshData();
                            }

                            ComputeTotal();
                        }
                    }
                }
                
                if (e.KeyCode == Keys.Down)
                {
                    if (grdViewSR.IsLastRow)
                    {
                        string sItemCode = "";
                        iFocusedRowHandle = grdViewSR.FocusedRowHandle;
                        sItemCode = grdViewSR.GetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["ItemCode"]).ToString();

                        if (sItemCode != "" && (txtStatus.Text == "Draft"))
                        {
                            grdViewSR.AddNewRow();

                            grdViewSR.FocusedColumn = grdViewSR.Columns["ItemCode"];
                            grdViewSR.ShowEditor();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void btnSearchItemCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            int iFocusedRowHandle = -1;
            iFocusedRowHandle = grdViewSR.FocusedRowHandle;

            
            FND_ITM_SO _FindItemInSO = new FND_ITM_SO();

            _FindItemInSO.ConnectionString = this.ConnectionString;
            _FindItemInSO.CustomerCode = this.txtCardCode.Text;

            foreach (DataRow oRows in this.ReturnLineItems.Rows)
            {
                _FindItemInSO.ItemCodes.Add(oRows["ItemCode"].ToString());
            }

            _FindItemInSO.ShowDialog();

            if (_FindItemInSO.ItemCode != null)
            {
                if (_FindItemInSO.ItemCode.Trim() != "")
                {
                    UoMManager oUnitMeasureManager = new UoMManager();
                    oUnitMeasureManager.ConnectionString = this.ConnectionString;
                    oUnitMeasureManager.Open();

                    BindUoM(_FindItemInSO.ItemCode, cboUnitMeasure);

                    int _unitMeasureCount = 0;
                    double _PackSize = 1;
                    string _unitMeasure = "";

                    _unitMeasureCount = cboUnitMeasure.Items.Count;

                    if (_unitMeasureCount > 0)
                    {
                        _unitMeasure = _FindItemInSO.UOM;
                        _PackSize = oUnitMeasureManager.GetPackSize(_FindItemInSO.ItemCode, _unitMeasure);


                    }
                    else
                    {
                        _unitMeasure = _FindItemInSO.UOM;
                        _PackSize = 1;
                    }

                    oUnitMeasureManager.Close();

                    grdViewSR.SetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["PriceListCode"], _FindItemInSO.PriceListCode);
                    grdViewSR.SetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["ItemCode"], _FindItemInSO.ItemCode);
                    grdViewSR.SetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["ItemDesc"], _FindItemInSO.Description);
                    grdViewSR.SetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["UoM"], _FindItemInSO.UOM);
                    grdViewSR.SetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["UnitPrice"], _FindItemInSO.UnitPrice);
                    
                    if (Convert.ToDouble(this.VATRate) == 0)
                    {
                        grdViewSR.SetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["UnitPrice"], _FindItemInSO.UnitPrice);
                        
                    }
                    else
                    {

                        grdViewSR.SetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["UnitPrice"], _FindItemInSO.UnitPrice);
                        
                    }

                    int _ZeroVAL = 0;
                    grdViewSR.SetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["CQty"], _PackSize);
                    grdViewSR.SetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["DiscPrcnt"], _ZeroVAL);
                    grdViewSR.SetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["Discount"], _ZeroVAL);
                    grdViewSR.SetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["TotalLineDisc"], _ZeroVAL);
                    bool IsChecked = false;
                    grdViewSR.SetRowCellValue(iFocusedRowHandle, grdViewSR.Columns["IsFree"], IsChecked);

                    BindLotNumber(_FindItemInSO.ItemCode, cboLotNumber);
                }
                else
                {
                    grdViewSR.CancelUpdateCurrentRow();
                    if (grdViewSR.RowCount <= 0)
                    {
                        grdViewSR.AddNewRow();
                    }
                }
            }
            else
            {
                grdViewSR.CancelUpdateCurrentRow();
                if (grdViewSR.RowCount <= 0)
                {
                    grdViewSR.AddNewRow();
                }
            }

            _FindItemInSO.Dispose();
        }

        private void btnSearchItemCode_KeyDown(object sender, KeyEventArgs e)
        {
            this.UsedKey = e.KeyCode;

            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab)
            {
                string _ItemGUID = System.Guid.NewGuid().ToString();

                DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

                try
                {
                    string sItemCode = oButtonEdit.Text;
                    ItemManager oManager = new ItemManager();

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    DataTable dt = oManager.GetSlsItemByCodeWithPrice(this.DefaultPriceList, sItemCode);

                    oManager.Close();

                    if (dt.Rows.Count > 0)
                    {
                        #region If Has Rows
                        var items = from row in dt.AsEnumerable()
                                    select new
                                    {
                                        ItemCode = row["ItemCode"].ToString(),
                                        Dscription = row["Description"].ToString(),
                                        UoM = row["UNITOFMEASURE"].ToString(),
                                        UnitPrice = row["UNITPRICE"].ToString()
                                    };


                        int iCount = -1;
                        int[] oRow = grdViewSR.GetSelectedRows();

                        iCount = oRow[0];

                        string sVAT = this.VATCode.Trim() != "" ? this.VATCode : "N/A";
                        double _ZeroVAL = 0;
                        int iRowIndex = grdViewSR.FocusedRowHandle;

                        if (iRowIndex < 0)
                        {
                            iRowIndex = 0;
                        }

                        int iCountQty = 0;

                        try
                        {
                            iCountQty = Convert.ToInt32(grdViewSR.GetRowCellValue(grdViewSR.FocusedRowHandle, grdViewSR.Columns["Qty"]));
                        }
                        catch
                        {
                        }

                        int iCountCQty = 0;

                        try
                        {
                            iCountCQty = Convert.ToInt32(grdViewSR.GetRowCellValue(grdViewSR.FocusedRowHandle, grdViewSR.Columns["CQty"]));
                        }
                        catch
                        {
                        }

                        foreach (var oUnit in items)
                        {
                            BindUoM(oUnit.ItemCode, cboUnitMeasure);

                            int _unitMeasureCount = 0;

                            string _unitMeasure = "";
                            double _PackSize = 0;
                            UoMManager oUnitMeasureManager = new UoMManager();
                            oUnitMeasureManager.ConnectionString = this.ConnectionString;
                            oUnitMeasureManager.Open();
                            _unitMeasureCount = cboUnitMeasure.Items.Count;

                            if (_unitMeasureCount > 0)
                            {
                                _unitMeasure = oUnit.UoM;
                                _PackSize = oUnitMeasureManager.GetPackSize(oUnit.ItemCode, _unitMeasure);
                            }
                            else
                            {
                                _unitMeasure = oUnit.UoM;
                                _PackSize = 1;
                            }

                            oUnitMeasureManager.Close();
                            grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["PriceListCode"], this.DefaultPriceList);
                            grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["ItemCode"], oUnit.ItemCode);
                            grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["ItemDesc"], oUnit.Dscription);
                            grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["UoM"], oUnit.UoM);
                            if (iCountQty == 0)
                            {
                                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Qty"], 1);
                            }

                            grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["CQty"], _PackSize);
                            grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["UnitPrice"], oUnit.UnitPrice);
                            grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Discount"], _ZeroVAL);
                            grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["DiscPrcnt"], _ZeroVAL);
                            grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Discount"], _ZeroVAL);
                            grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["TotalLineDisc"], _ZeroVAL);
                            grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["ItemGuID"], _ItemGUID);
                            BindLotNumber(oUnit.ItemCode, cboLotNumber);
                        }
                        #endregion


                        #region Applying in Line Item Amount Computation
                        double _UNITPRICE = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["UnitPrice"]).ToString());
                        double _TOTAL_DISCOUNT = 1 * Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["Discount"]).ToString());

                        double _AMOUNT = (1 * _UNITPRICE) - _TOTAL_DISCOUNT;
                        grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                        grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Amount"], _AMOUNT);

                        ComputeTotal();
                        ApplyVolumeDiscount();
                        #endregion


                        grdViewSR.FocusedColumn = grdViewSR.Columns["Qty"];
                        
                        return;

                    }
                    else
                    {

                        if (!(this.UsedKey == Keys.Escape))
                        {


                            if (sItemCode.Trim() != "")
                            {
                                MessageBox.Show("No item found in the Price List!!!", "Item Code", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                grdViewSR.FocusedColumn = grdViewSR.Columns["ItemCode"];

                                return;
                            }
                            this.UsedKey = Keys.None;
                        }
                        else
                        {
                            this.UsedKey = Keys.None;
                        }
                    }
                }
                catch
                {
                }
            }

            
        }

        private void txtQty_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Tab)
            {
                try
                {
                    int iCount = -1;
                    int[] oRow = grdViewSR.GetSelectedRows();
                    iCount = oRow[0];

                    DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                    double _QUANTITY = Convert.ToDouble(oTextQty.Text);
                    double _CQUANTITY = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["CQty"]).ToString());
                    string _ITEMCODE = grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["ItemCode"]).ToString();
                    double _UNITPRICE = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["UnitPrice"]).ToString());
                    double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["Discount"]).ToString());

                    double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;
                    grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Amount"], _AMOUNT);
                    bool IsChecked = false;
                    grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["IsFree"], IsChecked);
                    ComputeTotal();
                    ApplyVolumeDiscount();

                    grdViewSR.FocusedColumn = grdViewSR.Columns["Reason"];

                }
                catch
                {
                }
            }

            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    int iCount = -1;
                    int[] oRow = grdViewSR.GetSelectedRows();
                    iCount = oRow[0];

                    DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                    double _QUANTITY = Convert.ToDouble(oTextQty.Text);
                    double _CQUANTITY = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["CQty"]).ToString());
                    string _ITEMCODE = grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["ItemCode"]).ToString();
                    double _UNITPRICE = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["UnitPrice"]).ToString());
                    double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) *  Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["Discount"]).ToString());

                    double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;
                    grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Amount"], _AMOUNT);
                    bool IsChecked = false;
                    grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["IsFree"], IsChecked);
                    ComputeTotal();
                    ApplyVolumeDiscount();

                    grdViewSR.FocusedColumn = grdViewSR.Columns["Reason"];
                    
                }
                catch
                {
                }
            }

            if (e.KeyCode == Keys.Down)
            {
                try
                {
                    int iCount = -1;
                    int[] oRow = grdViewSR.GetSelectedRows();
                    iCount = oRow[0];

                    DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                    double _QUANTITY = Convert.ToDouble(oTextQty.Text);
                    double _CQUANTITY = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["CQty"]).ToString());
                    string _ITEMCODE = grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["ItemCode"]).ToString();
                    double _UNITPRICE = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["UnitPrice"]).ToString());
                    double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["Discount"]).ToString());

                    double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;
                    grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Amount"], _AMOUNT);
                    bool IsChecked = false;
                    grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["IsFree"], IsChecked);
                    ComputeTotal();
                    ApplyVolumeDiscount();

                    grdViewSR.FocusedColumn = grdViewSR.Columns["Reason"];

                }
                catch
                {
                }
            }
        }

        private void txtLineDiscount_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int iCount = -1;
                int[] oRow = grdViewSR.GetSelectedRows();

                iCount = oRow[0];
                DevExpress.XtraEditors.TextEdit oTxtLineDiscount = (DevExpress.XtraEditors.TextEdit)sender;

                double _lineDiscount = Convert.ToDouble(oTxtLineDiscount.Text);
                double _UnitPrice = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["UnitPrice"]).ToString());
                double _Qty = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["Qty"]).ToString());
                double _CQty = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["CQty"]).ToString());
                double _Percentage = 0;

                _Percentage = _lineDiscount / _UnitPrice;

                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["DiscPrcnt"], (_Percentage * 100));
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["TotalLineDisc"], (_Qty * _CQty) * _lineDiscount);

                double _TotalDiscount = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["TotalLineDisc"]).ToString());

                double _Amount = ((_Qty *_CQty )  * _UnitPrice) - _TotalDiscount;
                
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Amount"], _Amount);

                ComputeTotal();
                ApplyVolumeDiscount();
            }
        }

        private void txtLineDiscPercent_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int iCount = -1;
                int[] oRow = grdViewSR.GetSelectedRows();

                iCount = oRow[0];
                DevExpress.XtraEditors.TextEdit oTxtDiscPrcnt = (DevExpress.XtraEditors.TextEdit)sender;

                double _discPrcnt = Convert.ToDouble(oTxtDiscPrcnt.Text);
                double _UnitPrice = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["UnitPrice"]).ToString());
                double _Qty = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["Qty"]).ToString());
                double _CQty = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["CQty"]).ToString());

                double _LineDiscount = _UnitPrice * (_discPrcnt/100);
                double _TotalDiscount = (_Qty * _CQty) * _LineDiscount;

                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Discount"], _LineDiscount);
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["TotalLineDisc"], _TotalDiscount);

                double _Amount = ((_Qty * _CQty) * _UnitPrice) - _TotalDiscount;
                
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Amount"], _Amount);

                ComputeTotal();
                ApplyVolumeDiscount();
            }
        }
        
        private void btnAdd_Click(object sender, EventArgs e)
        {
            SalesReturnManager oManager = new SalesReturnManager();
            SalesReturnUnit oUnit = new SalesReturnUnit();

            RemoveBlankLastRowFirst();
            if (btnAdd.Text == "Add")
            {
                #region Header Sales Return

                txtDocumentNumber.Text = GetNewSeries();
                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;
                
                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.ReferenceSINo = txtRefSINo.Text;
                oUnit.Ref1 = txtRef1.Text;
                oUnit.Ref2 = txtRef2.Text;
                oUnit.Ref3 = txtRef3.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                

                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;
                oUnit.ReturnType = cboReturnType.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }



                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.CreatedBy = this.ActiveUserID;
                oUnit.ModifiedBy = this.ActiveUserID;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());

                #endregion

                oUnit.LineItems = this.ReturnLineItems;
                
                #region Adding Part
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                if (oManager.IsDocumentExists(txtDocumentNumber.Text) == false)
                {

                    System.Data.SqlClient.SqlException ex = oManager.AddReturn(oUnit);

                    if (ex == null)
                    {
                        btnAdd.Text = "Ok";
                        MainMenu oForm = (MainMenu)this.MdiParent;

                        oForm.ErrMsg.ImageIndex = 8;
                        oForm.ErrMsg.Caption = "Adding document is successfull!!!";
                        oForm.timer1.Enabled = true;


                        if (txtRefSINo.Text.Trim() != "")
                        {
                            InvoiceManager oInvoice = new InvoiceManager();

                            oInvoice.ConnectionString = this.ConnectionString;
                            oInvoice.Open();

                            oInvoice.SetInvoiceInProcess(txtRefSINo.Text);

                            oInvoice.Close();
                            
                        }
                        else
                        {
                            DeliveryManager oDR = new DeliveryManager();

                            oDR.ConnectionString = this.ConnectionString;
                            oDR.Open();

                            oDR.SetDRInProcess(txtReference.Text);

                            oDR.Close();

                        }

                    }
                    else
                    {
                        MessageBox.Show(ex.Message.ToString(), "Notebook Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MainMenu oForm = (MainMenu)this.MdiParent;

                    oForm.ErrMsg.ImageIndex = 6;
                    oForm.ErrMsg.Caption = "Document is already exists!!!";
                    oForm.timer1.Enabled = true;
                }
                oManager.Close();

                
                #endregion

            }
            else if(btnAdd.Text == "Update")
            {

                #region Header Sales Quote

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.ReferenceSINo = txtRefSINo.Text;
                oUnit.Ref1 = txtRef1.Text;
                oUnit.Ref2 = txtRef2.Text;
                oUnit.Ref3 = txtRef3.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                //if (cboLocation.SelectedValue != null)
                //{
                //    oUnit.Location = cboLocation.SelectedValue.ToString();
                //}
                //else
                //{
                //    oUnit.Location = "";
                //}

                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;
                oUnit.ReturnType = cboReturnType.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                oUnit.WithHoldingTax = Convert.ToDouble(txtWithHoldingTax.Text);
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }



                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.ModifiedBy = this.ActiveUserID;
                #endregion

                oUnit.LineItems = this.ReturnLineItems;

                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                System.Data.SqlClient.SqlException ex = oManager.UpdateReturn(oUnit);
                oManager.Close();

                if (ex == null)
                {
                    MainMenu oForm = (MainMenu)this.MdiParent;

                    oForm.ErrMsg.ImageIndex = 8;
                    oForm.ErrMsg.Caption = "Updating document is successfull!!!";
                    oForm.timer1.Enabled = true;
                    btnAdd.Text = "Ok";
                }
                else
                {
                    MessageBox.Show(ex.Message.ToString(), "Notebook Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                #endregion

               
            }
            else
            {
                this.Close();
            }

           

        }

        private void txtDiscount_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc1.Text.Trim() != "0%" && txtDisc1.Text.Trim() != "" && txtDisc1.Text.Trim() != ".00%" && txtDisc1.Text.Trim() != "0" && txtDisc1.Text.Trim() != ".00")
            {
                txtDisc2.Enabled = true;
            }
            else
            {
                txtDisc2.Enabled = false;
                txtDisc2.Text = "0%";
                txtDisc3.Enabled = false;
                txtDisc3.Text = "0%";
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDisc2_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc2.Text.Trim() != "0%" && txtDisc2.Text.Trim() != "" && txtDisc2.Text.Trim() != ".00%" && txtDisc2.Text.Trim() != "0" && txtDisc2.Text.Trim() != ".00")
            {
                txtDisc3.Enabled = true;
            }
            else
            {
                txtDisc3.Enabled = false;
                txtDisc3.Text = "0%";
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDisc3_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc3.Text.Trim() != "0%" && txtDisc3.Text.Trim() != "" && txtDisc3.Text.Trim() != ".00%" && txtDisc3.Text.Trim() != "0" && txtDisc3.Text.Trim() != ".00")
            {
                txtDisc4.Enabled = true;
            }
            else
            {
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDisc4_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc3.Text.Trim() != "0%" && txtDisc3.Text.Trim() != "" && txtDisc3.Text.Trim() != ".00%" && txtDisc3.Text.Trim() != "0" && txtDisc3.Text.Trim() != ".00")
            {
                txtDisc4.Enabled = true;
            }
            else
            {
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDiscount_Leave(object sender, EventArgs e)
        {
            try
            {
                double iCheck = Convert.ToDouble(txtDisc1.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc1.Text = string.Format("{0:###.00}", txtDisc1.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc1.Text = "0%";
                }
            }
            catch
            {
                MessageBox.Show("Doesn't allow character please insert number only!!!", "Error Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDisc1.Text = "0%";
            }
        }

        private void txtDisc2_Leave(object sender, EventArgs e)
        {
            try
            {
                double iCheck = Convert.ToDouble(txtDisc2.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc2.Text = string.Format("{0:###.00}", txtDisc2.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc2.Text = "0%";
                }
            }
            catch
            {
                MessageBox.Show("Doesn't allow character please insert number only!!!", "Error Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDisc2.Text = "0%";
            }
        }

        private void txtDisc3_Leave(object sender, EventArgs e)
        {
            try
            {
                double iCheck = Convert.ToDouble(txtDisc3.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc3.Text = string.Format("{0:###.00}", txtDisc3.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc3.Text = "0%";
                }
            }
            catch
            {
                MessageBox.Show("Doesn't allow character please insert number only!!!", "Error Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDisc3.Text = "0%";
            }
        }

        private void txtDisc4_Leave(object sender, EventArgs e)
        {
            try
            {
                double iCheck = Convert.ToDouble(txtDisc4.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc4.Text = string.Format("{0:###.00}", txtDisc4.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc4.Text = "0%";
                }
            }
            catch
            {
                MessageBox.Show("Doesn't allow character please insert number only!!!", "Error Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDisc4.Text = "0%";
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtQty_Leave(object sender, EventArgs e)
        {
            try
            {
                ComputeTotal();
                ApplyVolumeDiscount();
            }
            catch
            {
            }
        }

        private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            ComputeTotal();
            ApplyVolumeDiscount();
        }

        private void xtraScrollableControl1_Click(object sender, EventArgs e)
        {

        }

        private void txtDiscount_Enter(object sender, EventArgs e)
        {
            txtDisc1.Text = txtDisc1.Text.Replace("%", "");
        }

        private void txtDisc2_Enter(object sender, EventArgs e)
        {
            txtDisc2.Text = txtDisc2.Text.Replace("%", "");
        }

        private void txtDisc3_Enter(object sender, EventArgs e)
        {
            txtDisc3.Text = txtDisc3.Text.Replace("%", "");
        }

        private void txtDisc4_Enter(object sender, EventArgs e)
        {
            txtDisc4.Text = txtDisc4.Text.Replace("%", "");
        }

        private void txtDiscount_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void txtDisc2_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void txtDisc3_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void txtDisc4_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void txtTotalDiscount_Leave(object sender, EventArgs e)
        {
        }

        private void chkFree_CheckedChanged(object sender, EventArgs e)
        {
            int iCount = -1;
            int[] oRow = grdViewSR.GetSelectedRows();
            
            iCount = oRow[0];
            DevExpress.XtraEditors.CheckEdit oCheckBox = (DevExpress.XtraEditors.CheckEdit)sender;

            bool IsChecked = oCheckBox.Checked;
            int _ZeroVAL = 0;
            grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["IsFree"], IsChecked);
            if (IsChecked == true)
            {
                
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["DiscPrcnt"], _ZeroVAL);
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Discount"], _ZeroVAL);
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["TotalLineDisc"], _ZeroVAL);
                
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Amount"], _ZeroVAL);
            }
            else
            {
                string sItemCode = grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["ItemCode"]).ToString();
                double dNetPrice = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["UnitPrice"]).ToString());
                double iQty = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["Qty"]).ToString());
                double iCQty = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["CQty"]).ToString());
                
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["DiscPrcnt"], _ZeroVAL);
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Discount"], _ZeroVAL);
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["TotalLineDisc"], _ZeroVAL);
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Amount"], (iQty * iCQty) * Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["UnitPrice"])));
            }

            //OrderLineItems.AcceptChanges();
            ComputeTotal();
            ApplyVolumeDiscount();
        }

        #endregion

        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (txtDocumentNumber.Text != "##########" )
            {
                if (txtStatus.Text == "Draft")
                {
                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                    {
                        PostOrder(txtDocumentNumber.Text);
                    }

                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        CancelOrder(txtDocumentNumber.Text);
                    }
                }
                else
                {
                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        CloseOrder(txtDocumentNumber.Text);
                    }
                }
            }
            
        }

        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft")
            {
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
                EnableControls();

                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = true;
                addRowToolStripMenuItem.Enabled = true;
                deleteRowToolStripMenuItem.Enabled = true;

                
            }
            if (txtStatus.Text == "Canceled" || txtStatus.Text == "Closed")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
                DisableControls();
                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;
            }

            if (txtStatus.Text == "Posted")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();
                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;
            }

            if (txtStatus.Text == "Open")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();
                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;
            }
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private void ribbonControl1_Click(object sender, EventArgs e)
        {

        }

        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "")
            {
                e.DisplayText = (e.RowHandle + 1).ToString();

            }
        }

        private void SalesReturn_Shown(object sender, EventArgs e)
        {
            gridControl1.Select();
            grdViewSR.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
            grdViewSR.FocusedColumn = grdViewSR.Columns["ItemCode"];
            grdViewSR.ShowEditor();


            txtCardCode.Focus();

            string _USR_AUTHORIZATION = ApplyAuthorization();
            if (_USR_AUTHORIZATION == "No Access")
            {
                btnCancel_Click(sender, e);
            }

        }

        private void btnSearchItemCode_Leave(object sender, EventArgs e)
        {
            
        }

        private void txtCardCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddressBookManager oManager = new AddressBookManager();
                TaxManager oTxManager = new TaxManager();
                DataTable _TABLE = new DataTable();

                try
                {

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    _TABLE = oManager.GetByBPCode(txtCardCode.Text, "Customer");

                    oManager.Close();

                    int iCount = _TABLE.Rows.Count;

                    if (iCount == 0)
                    {
                        #region if no data return during enter
                        FND_BP _SearchBP = new FND_BP();

                        AddressBookManager oBPManager = new AddressBookManager();

                        try
                        {
                            _SearchBP.ConnectionString = this.ConnectionString;
                            _SearchBP.BusinessPartnerType = "Customer";
                            _SearchBP.SetSearchByBPCode(txtCardCode.Text);

                            _SearchBP.ShowDialog();
                            txtStoreCode.Text = _SearchBP.StoreCode;
                            txtCardCode.Text = _SearchBP.CardCode;
                            txtCardName.Text = _SearchBP.CardName;
                            txtBillTo.Text = _SearchBP.Address;
                            //txtPaymentTerms.Text = _SearchBP.PaymentTerm.ToString();
                            txtContactPerson.Text = _SearchBP.ContactPerson;
                            this.DefaultPriceList = _SearchBP.PriceList;
                            this.WithHoldingTaxRate = _SearchBP.WithHoldingTax;
                            this.VATCode = _SearchBP.VATCode;
                            
                            try
                            {
                                txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                                txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                                txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                                txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                            }
                            catch
                            {
                            }


                            oTxManager.ConnectionString = this.ConnectionString;
                            oTxManager.Open();


                            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;



                            oTxManager.Close();

                            if (_SearchBP.BuyerSalesMan != "")
                            {
                                cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                            }

                            _SearchBP.Dispose();
                        }
                        catch
                        {
                        }
                        #endregion
                        return;
                    }

                    DataRow oRow = _TABLE.Rows[0];


                    txtStoreCode.Text = oRow["StoreCode"].ToString();
                    txtCardCode.Text = oRow["BPCode"].ToString();
                    txtCardName.Text = oRow["BPName"].ToString();
                    txtBillTo.Text = oRow["Address"].ToString();
                    //txtPaymentTerms.Text = oRow["PaymentTerm"].ToString();
                    txtContactPerson.Text = oRow["ContactPerson"].ToString(); ;
                    this.DefaultPriceList = oRow["PriceList"].ToString(); ;
                    this.VATCode = oRow["VATCode"].ToString();
                    try
                    {
                        txtDisc1.Text = oRow["Disc1"].ToString() + "%";
                        txtDisc2.Text = oRow["Disc2"].ToString() + "%";
                        txtDisc3.Text = oRow["Disc3"].ToString() + "%";
                        txtDisc4.Text = oRow["Disc4"].ToString() + "%";
                    }
                    catch
                    {
                    }

                    //cboCurrency.Text 
                    oTxManager.ConnectionString = this.ConnectionString;
                    oTxManager.Open();


                    this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                    this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;


                    oTxManager.Close();

                    if (oRow["SMCODE"].ToString() != "")
                    {
                        cboSalesman.EditValue = oRow["SMCODE"].ToString();
                    }
                }
                catch
                {
                }
            }
        }

        private void cboReason_Leave(object sender, EventArgs e)
        {
            
        }

        private void cboLotNumber_Leave(object sender, EventArgs e)
        {
            
        }

        private void cboUnitMeasure_EditValueChanged(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.ComboBoxEdit oCboUoM = (DevExpress.XtraEditors.ComboBoxEdit)sender;
            string sUoM = "";
            try
            {
                sUoM = Convert.ToString(oCboUoM.Text);
            }
            catch
            {
                sUoM = "";
            }
            if (sUoM != "")
            {
                grdViewSR.SetRowCellValue(grdViewSR.FocusedRowHandle, grdViewSR.Columns["UoM"], sUoM);
            }
        }

        private void cboUnitMeasure_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sItemCode = "";
            string sUoM = "";

            int iFocusRowHandle = grdViewSR.FocusedRowHandle;

            try
            {
                sItemCode = grdViewSR.GetRowCellValue(iFocusRowHandle, grdViewSR.Columns["ItemCode"]).ToString();

                DevExpress.XtraEditors.ComboBoxEdit oCombo = (DevExpress.XtraEditors.ComboBoxEdit)sender;

                sUoM = oCombo.Text;

                UoMManager oManager = new UoMManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                double _PackSize = oManager.GetPackSize(sItemCode, sUoM);
                oManager.Close();

                grdViewSR.SetRowCellValue(iFocusRowHandle, grdViewSR.Columns["CQty"], _PackSize);



                int iCount = -1;
                int[] oRow = grdViewSR.GetSelectedRows();
                iCount = oRow[0];

                DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                double _QUANTITY = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["Qty"]).ToString());
                double _CQUANTITY = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["CQty"]).ToString());
                string _ITEMCODE = grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["ItemCode"]).ToString();
                double _UNITPRICE = Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["UnitPrice"]).ToString());
                double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["Discount"]).ToString());

                double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["Amount"], _AMOUNT);
                bool IsChecked = false;
                grdViewSR.SetRowCellValue(iCount, grdViewSR.Columns["IsFree"], IsChecked);
                ComputeTotal();
                ApplyVolumeDiscount();
            }
            catch
            {
            }

        }

        private void cboReason_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {

                DevExpress.XtraEditors.ComboBoxEdit oCboReason = (DevExpress.XtraEditors.ComboBoxEdit)sender;

                grdViewSR.SetRowCellValue(grdViewSR.FocusedRowHandle, grdViewSR.Columns["Reason"], oCboReason.Text);
                
                grdViewSR.FocusedColumn = grdViewSR.Columns["LotNumber"];
            }
            if (e.KeyCode == Keys.Tab)
            {
                DevExpress.XtraEditors.ComboBoxEdit oCboReason = (DevExpress.XtraEditors.ComboBoxEdit)sender;

                grdViewSR.SetRowCellValue(grdViewSR.FocusedRowHandle, grdViewSR.Columns["Reason"], oCboReason.Text);
                grdViewSR.FocusedColumn = grdViewSR.Columns["LotNumber"];
            }
        }

        private void txtReference_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

        }

        private void txtQty_EditValueChanged(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.TextEdit textQty = (DevExpress.XtraEditors.TextEdit)sender;
            int iQty = 0;
            try
            {
                iQty = Convert.ToInt16(textQty.Text);
            }
            catch
            {
                iQty = 0;
            }
            grdViewSR.SetRowCellValue(grdViewSR.FocusedRowHandle, grdViewSR.Columns["Qty"], iQty);
        }

        private void SalesReturn_Resize(object sender, EventArgs e)
        {
            if (this.Width > 858)
            {
                lblDocNo.Left = this.Width - 274;
                txtDocumentNumber.Left = this.Width - 153;

                lblDocStatus.Left = this.Width - 274;
                txtStatus.Left = this.Width - 153;

                lblPostDate.Left = this.Width - 274;
                dtPostDate.Left = this.Width - 153;

                lblValidUntilDeliveryDate.Left = this.Width - 274;
                dtDeliveryDate.Left = this.Width - 153;

                lblDocumentDate.Left = this.Width - 274;
                dtDocDate.Left = this.Width - 153;

                lblReturnType.Left = this.Width - 274;
                cboReturnType.Left = this.Width - 153;

                gridControl1.Width = this.Width - 41;

                lblGrossAmount.Left = this.Width - 458;
                txtGrossAmount.Left = this.Width - 350;

                lblTotalLineDiscount.Left = this.Width - 458;
                txtTotalLineDiscount.Left = this.Width - 350;

                lblDiscount.Left = this.Width - 458;
                txtDisc1.Left = this.Width - 350;
                txtDisc2.Left = this.Width - 298;
                txtDisc3.Left = this.Width -243;
                txtDisc4.Left = this.Width -188;
                txtTotalDiscount.Left = this.Width - 133;

                lblVAT.Left = this.Width - 458;
                txtVAT.Left = this.Width - 350;

                lblNetAmt.Left = this.Width - 458;
                txtNetAmt.Left = this.Width - 350;

                lblWithHoldingTax.Left = this.Width - 243;
                txtWithHoldingTax.Left = this.Width - 133;

            }
            else
            {
                lblDocNo.Left = 584;
                txtDocumentNumber.Left = 705;

                lblDocStatus.Left = 584;
                txtStatus.Left = 705;

                lblPostDate.Left = 584;
                dtPostDate.Left = 705;

                lblValidUntilDeliveryDate.Left = 584;
                dtDeliveryDate.Left = 705;

                lblDocumentDate.Left = 584;
                dtDocDate.Left = 705;

                lblReturnType.Left = 584;
                cboReturnType.Left = 705;

                gridControl1.Width = 817;

                lblGrossAmount.Left = 400;
                txtGrossAmount.Left = 508;

                lblTotalLineDiscount.Left = 400;
                txtTotalLineDiscount.Left = 508;

                lblDiscount.Left = 400;
                txtDisc1.Left = 508;
                txtDisc2.Left = 560;
                txtDisc3.Left = 615;
                txtDisc4.Left = 670;
                txtTotalDiscount.Left = 725;

                lblVAT.Left = 400;
                txtVAT.Left = 508;

                lblNetAmt.Left = 400;
                txtNetAmt.Left = 508;
                lblWithHoldingTax.Left = 615;
                txtWithHoldingTax.Left = 725;
            }

            if (this.Height > 575)
            {
                gridControl1.Height = this.Height - 391;

                lblSalesMan.Top = this.Height - 200;
                cboSalesman.Top = this.Height - 200;

                lblRemarks.Top = this.Height - 175;
                txtRemarks.Top = this.Height - 175;

                btnCancel.Top = this.Height - 99;
                btnAdd.Top = this.Height - 99;

                lblGrossAmount.Top = this.Height - 200;
                txtGrossAmount.Top = this.Height - 200;

                lblTotalLineDiscount.Top = this.Height - 175;
                txtTotalLineDiscount.Top = this.Height - 175;

                lblDiscount.Top = this.Height - 149;
                txtDisc1.Top = this.Height - 149;
                txtDisc2.Top = this.Height - 149;
                txtDisc3.Top = this.Height - 149;
                txtDisc4.Top = this.Height - 149;
                txtTotalDiscount.Top = this.Height - 149;

                lblVAT.Top = this.Height - 123;
                txtVAT.Top = this.Height - 123;

                lblNetAmt.Top = this.Height - 97;
                txtNetAmt.Top = this.Height - 97;

                lblWithHoldingTax.Top = this.Height - 123;
                txtWithHoldingTax.Top = this.Height - 123;

            }
            else
            {
                gridControl1.Height = 184;

                lblSalesMan.Top = 375;
                cboSalesman.Top = 375;

                lblRemarks.Top = 400;
                txtRemarks.Top = 400;

                btnCancel.Top = 476;
                btnAdd.Top = 476;

                lblGrossAmount.Top = 375;
                txtGrossAmount.Top = 375;

                lblTotalLineDiscount.Top = 400;
                txtTotalLineDiscount.Top = 400;

                lblDiscount.Top = 426;
                txtDisc1.Top = 426;
                txtDisc2.Top = 426;
                txtDisc3.Top = 426;
                txtDisc4.Top = 426;
                txtTotalDiscount.Top = 426;

                lblVAT.Top = 452;
                txtVAT.Top = 452;

                lblNetAmt.Top = 478;
                txtNetAmt.Top = 478;

                lblWithHoldingTax.Top = 452;
                txtWithHoldingTax.Top = 452;



            }
        }

        private void gridControl1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                cntxtRightClickMenu.Show(Cursor.Position);
            }
        }

        private void addRowToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (grdViewSR.IsLastRow == false)
            {
                grdViewSR.MoveLast();
            }

            string _ItemCode = "";

            _ItemCode = grdViewSR.GetRowCellValue(grdViewSR.FocusedRowHandle, grdViewSR.Columns["ItemCode"]).ToString();

            if (_ItemCode.Trim() == "")
            {
                MessageBox.Show("New row is already exists!!!", "Add Row", MessageBoxButtons.OK, MessageBoxIcon.Information);

                grdViewSR.MoveLast();
                grdViewSR.FocusedColumn = grdViewSR.Columns["ItemCode"];
                grdViewSR.ShowEditor();
            }
            else
            {
                grdViewSR.AddNewRow();

                txtCardCode.Focus();

                gridControl1.Select();
                grdViewSR.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                grdViewSR.FocusedColumn = grdViewSR.VisibleColumns[1];
                grdViewSR.ShowEditor();
            }
        }

        private void insertNewRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int iRowHandle = grdViewSR.FocusedRowHandle;

            DataTable dt = this.ReturnLineItems;
            DataRow _BlankRow = dt.NewRow();

            dt.Rows.InsertAt(_BlankRow, iRowHandle);

            gridControl1.DataSource = dt;
            gridControl1.Refresh();

            grdViewSR.FocusedRowHandle = iRowHandle;
        }

        private void deleteRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int iCount = grdViewSR.FocusedRowHandle;


            if (txtStatus.Text == "Draft")
            {
                if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {

                    if (grdViewSR.IsLastRow)
                    {
                        string sItemCode = "";


                        iCount = grdViewSR.FocusedRowHandle;
                        sItemCode = grdViewSR.GetRowCellValue(iCount, grdViewSR.Columns["ItemCode"]).ToString();


                        if (sItemCode != "")
                        {
                            grdViewSR.DeleteRow(iCount);
                            grdViewSR.AddNewRow();
                        }


                        grdViewSR.RefreshData();

                    }
                    else
                    {


                        iCount = grdViewSR.FocusedRowHandle;

                        grdViewSR.DeleteRow(iCount);
                        grdViewSR.RefreshData();
                    }

                    ComputeTotal();
                }
            }
        }

        private void txtStoreCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddressBookManager oManager = new AddressBookManager();
                TaxManager oTxManager = new TaxManager();
                DataTable _TABLE = new DataTable();

                try
                {

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    _TABLE = oManager.GetByStoreCode(txtStoreCode.Text, "Customer");

                    oManager.Close();

                    int iCount = _TABLE.Rows.Count;

                    if (iCount == 0)
                    {
                        #region if no data return during enter
                        FND_BP _SearchBP = new FND_BP();

                        AddressBookManager oBPManager = new AddressBookManager();

                        try
                        {
                            _SearchBP.ConnectionString = this.ConnectionString;
                            _SearchBP.SearchIndex = 2;
                            _SearchBP.BusinessPartnerType = "Customer";
                            _SearchBP.SetSearchByStoreCode(txtStoreCode.Text);

                            _SearchBP.ShowDialog();

                            txtStoreCode.Text = _SearchBP.StoreCode;
                            txtCardCode.Text = _SearchBP.CardCode;
                            txtCardName.Text = _SearchBP.CardName;
                            txtBillTo.Text = _SearchBP.Address;
                            
                            txtContactPerson.Text = _SearchBP.ContactPerson;
                            this.DefaultPriceList = _SearchBP.PriceList;
                            this.VATCode = _SearchBP.VATCode;
                            try
                            {
                                txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                                txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                                txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                                txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                            }
                            catch
                            {
                            }


                            oTxManager.ConnectionString = this.ConnectionString;
                            oTxManager.Open();


                            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;



                            oTxManager.Close();

                            if (_SearchBP.BuyerSalesMan != "")
                            {
                                cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                            }

                            _SearchBP.Dispose();
                        }
                        catch
                        {
                        }
                        #endregion
                        return;
                    }

                    DataRow oRow = _TABLE.Rows[0];

                    txtStoreCode.Text = oRow["StoreCode"].ToString();
                    txtCardCode.Text = oRow["BPCode"].ToString();
                    txtCardName.Text = oRow["BPName"].ToString();
                    txtBillTo.Text = oRow["Address"].ToString();
                    
                    txtContactPerson.Text = oRow["ContactPerson"].ToString(); ;
                    this.DefaultPriceList = oRow["PriceList"].ToString(); ;
                    this.VATCode = oRow["VATCode"].ToString();

                    try
                    {
                        txtDisc1.Text = oRow["Disc1"].ToString() + "%";
                        txtDisc2.Text = oRow["Disc2"].ToString() + "%";
                        txtDisc3.Text = oRow["Disc3"].ToString() + "%";
                        txtDisc4.Text = oRow["Disc4"].ToString() + "%";
                    }
                    catch
                    {
                    }

                    //cboCurrency.Text 
                    oTxManager.ConnectionString = this.ConnectionString;
                    oTxManager.Open();


                    this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                    this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;


                    oTxManager.Close();

                    if (oRow["SMCODE"].ToString() != "")
                    {
                        cboSalesman.EditValue = oRow["SMCODE"].ToString();
                    }
                }
                catch
                {
                }
            }
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
           
        }

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            //string sItemCode = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["ItemCode"]).ToString();
            //string _ItemGUID = System.Guid.NewGuid().ToString();

            //DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

            //try
            //{
                
            //    ItemManager oManager = new ItemManager();

            //    oManager.ConnectionString = this.ConnectionString;
            //    oManager.Open();

            //    DataTable dt = oManager.GetSlsItemByCodeWithPrice(this.DefaultPriceList, sItemCode);

            //    oManager.Close();

            //    if (dt.Rows.Count > 0)
            //    {
            //        #region If Has Rows
            //        var items = from row in dt.AsEnumerable()
            //                    select new
            //                    {
            //                        ItemCode = row["ItemCode"].ToString(),
            //                        Dscription = row["Description"].ToString(),
            //                        UoM = row["UNITOFMEASURE"].ToString(),
            //                        UnitPrice = row["UNITPRICE"].ToString()
            //                    };


            //        int iCount = -1;
            //        int[] oRow = gridView1.GetSelectedRows();

            //        iCount = oRow[0];

            //        string sVAT = this.VATCode.Trim() != "" ? this.VATCode : "N/A";
            //        double _ZeroVAL = 0;
            //        int iRowIndex = gridView1.FocusedRowHandle;

            //        if (iRowIndex < 0)
            //        {
            //            iRowIndex = 0;
            //        }

            //        int iCountQty = 0;

            //        try
            //        {
            //            iCountQty = Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Qty"]));
            //        }
            //        catch
            //        {
            //        }

            //        int iCountCQty = 0;

            //        try
            //        {
            //            iCountCQty = Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["CQty"]));
            //        }
            //        catch
            //        {
            //        }

            //        foreach (var oUnit in items)
            //        {
            //            BindUoM(oUnit.ItemCode, cboUnitMeasure);

            //            int _unitMeasureCount = 0;

            //            string _unitMeasure = "";
            //            double _PackSize = 0;
            //            UoMManager oUnitMeasureManager = new UoMManager();
            //            oUnitMeasureManager.ConnectionString = this.ConnectionString;
            //            oUnitMeasureManager.Open();
            //            _unitMeasureCount = cboUnitMeasure.Items.Count;

            //            if (_unitMeasureCount > 0)
            //            {
            //                _unitMeasure = oUnit.UoM;
            //                _PackSize = oUnitMeasureManager.GetPackSize(oUnit.ItemCode, _unitMeasure);
            //            }
            //            else
            //            {
            //                _unitMeasure = oUnit.UoM;
            //                _PackSize = 1;
            //            }

            //            oUnitMeasureManager.Close();
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["PriceListCode"], this.DefaultPriceList);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], oUnit.ItemCode);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemDesc"], oUnit.Dscription);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], oUnit.UoM);
            //            if (iCountQty == 0)
            //            {
            //                gridView1.SetRowCellValue(iCount, gridView1.Columns["Qty"], 1);
            //            }

            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["CQty"], _PackSize);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], oUnit.UnitPrice);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["DiscPrcnt"], _ZeroVAL);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _ZeroVAL);
            //            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemGuID"], _ItemGUID);
            //            BindLotNumber(oUnit.ItemCode, cboLotNumber);
            //        }
            //        #endregion


            //        #region Applying in Line Item Amount Computation
            //        double _UNITPRICE = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
            //        double _TOTAL_DISCOUNT = 1 * Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Discount"]).ToString());

            //        double _AMOUNT = (1 * _UNITPRICE) - _TOTAL_DISCOUNT;
            //        gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
            //        gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _AMOUNT);

            //        ComputeTotal();
            //        ApplyVolumeDiscount();
            //        #endregion


            //        gridView1.FocusedColumn = gridView1.Columns["Qty"];

            //        return;

            //    }
            //    else
            //    {

            //        if (!(this.UsedKey == Keys.Escape))
            //        {


            //            if (sItemCode.Trim() != "")
            //            {
            //                MessageBox.Show("No item found in the Price List!!!", "Item Code", MessageBoxButtons.OK, MessageBoxIcon.Information);

            //                gridView1.FocusedColumn = gridView1.Columns["ItemCode"];

            //                return;
            //            }
            //            this.UsedKey = Keys.None;
            //        }
            //        else
            //        {
            //            this.UsedKey = Keys.None;
            //        }
            //    }
            //}
            //catch
            //{
            //}
        }

        private void distributionEntryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SalesReturnDistribution oForm = new SalesReturnDistribution();

            oForm.DocumentNumber = txtDocumentNumber.Text;
            oForm.ConnectionString = this.ConnectionString;

            oForm.ShowDialog();
        }

        private void duplicateToolMenu_Click(object sender, EventArgs e)
        {
            EnableControls();
            InitializeSeries();
            btnAdd.Text = "Add";
            txtStatus.Text = "Draft";
        }

        private void txtCardCode_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft" && btnAdd.Text == "Ok")
            {
                btnAdd.Text = "Update";
            }
        }

        private void cboLocation_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft" && btnAdd.Text == "Ok")
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtRef1_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft" && btnAdd.Text == "Ok")
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtRef2_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft" && btnAdd.Text == "Ok")
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtRef3_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft" && btnAdd.Text == "Ok")
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtShipTo_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft" && btnAdd.Text == "Ok")
            {
                btnAdd.Text = "Update";
            }
        }

        private void dtPostDate_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft" && btnAdd.Text == "Ok")
            {
                btnAdd.Text = "Update";
            }
        }

        private void dtDeliveryDate_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft" && btnAdd.Text == "Ok")
            {
                btnAdd.Text = "Update";
            }
        }

        private void dtDocDate_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft" && btnAdd.Text == "Ok")
            {
                btnAdd.Text = "Update";
            }
        }

        private void cboReturnType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft" && btnAdd.Text == "Ok")
            {
                btnAdd.Text = "Update";
            }
        }

        private void cboSalesman_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft" && btnAdd.Text == "Ok")
            {
                btnAdd.Text = "Update";
            }
        }

        private void txtRemarks_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft" && btnAdd.Text == "Ok")
            {
                btnAdd.Text = "Update";
            }
        }

        private void barNewEntry_ItemClick(object sender, ItemClickEventArgs e)
        {
            int iRowIndex = gridViewSalesRetAcctEntries.RowCount;
            if (gridViewSalesRetAcctEntries.RowCount <= 0)
            {
                gridViewSalesRetAcctEntries.AddNewRow();
                return;
            }

            gridViewSalesRetAcctEntries.FocusedRowHandle = iRowIndex - 1;
            try
            {
                string _AcctCode = "";


                if (gridViewSalesRetAcctEntries.GetRowCellValue(gridViewSalesRetAcctEntries.FocusedRowHandle, gridViewSalesRetAcctEntries.Columns["AcctCode"]) != null)
                {
                    _AcctCode = gridViewSalesRetAcctEntries.GetRowCellValue(gridViewSalesRetAcctEntries.FocusedRowHandle, gridViewSalesRetAcctEntries.Columns["AcctCode"]).ToString();
                }
                else
                {
                    _AcctCode = "";
                }

                if (_AcctCode.Trim() == "")
                {
                    return;
                }
            }
            catch { }


            gridViewSalesRetAcctEntries.AddNewRow();
        }

        private void barSaveARDistribution_ItemClick(object sender, ItemClickEventArgs e)
        {
            SalesReturnManager oManager = new SalesReturnManager();

            RemoveBlankLastGLAccounts();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            SqlException ex = oManager.AddDistributionEntries(this.txtDocumentNumber.Text, this.AccountingEntries);

            if (ex != null)
            {
                MessageBox.Show(ex.Message.ToString(), "Error Saving", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("Accounting is successfully saved!!!", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            oManager.Close();
        }

        private void barPostEntries_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void barClear_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.AccountingEntries = GetGLAcctStructure();

            gridSalesRetAcctEntries.DataSource = this.AccountingEntries;
            gridSalesRetAcctEntries.Refresh();
        }
    }
}

